<template>
  <!--  <cs/>-->
  <div class="Navbar">
    <Navbar/>
  </div>

  <div class="cont">
    <div class="con_rig">
      <div class="rig_con">
        <h1>{{ itms.title }}</h1>
      </div>
      <div class="con">
        <el-row :gutter="5">
          <el-col :span="columnSpan" v-for="(image, index) in itms.imageSrc" :key="index" class="item"
                  @click="openDialog(image)">
            <el-card shadow="hover">
              <div class="post-module-thumb">
                <el-image :src="image" class="post-thumb" alt="" fit="cover"/>
                <p class="caption">{{ itms.title }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div class="con_rig_but">
        <div class=" papy" @click="ordil" :class="{ disabled: piv }" v-if="!piv">
          <span class="" style="color: #fff;  font-weight: bold; margin-bottom: 10px;">购买本集:购买后即可观看完整内容且永久有效！后续更多精彩内容，请关注小站！</span>
        </div>
        <div class=" papy">
          <router-link :href="order" to="/order" style="color: #fff;   margin-bottom: 10px;">
            支持小站：购买收藏家，可获得更多精彩内容！
          </router-link>
        </div>
        <details class="wp-block-details is-layout-flow wp-block-details-is-layout-flow papy"
                 style="margin-bottom: 20px;">
          <summary>
            获取下载链接:
          </summary>
          <span>暂未开放下载链接，可联系站长获取！成为会员后期可下载</span>
        </details>
      </div>
      <div class="comment">
        <el-input class="input"
                  v-model="newComment"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入评论"
        />
        <el-button type="primary" @click="addComment">发表评论</el-button>
        <div class="comment-list">
          <div v-for="(comment, index) in commentList" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <img :src="comment.user_avatar" alt="avatar" class="sub-comment-avatar"/>
              <span class="comment-author">{{ comment.username }}</span>
              <span class="comment-meta">
                <span class="comment-time">{{ comment.created_at }}</span>
                <span class="comment-likes">{{ comment.likes }} 赞</span>
              </span>
            </div>
            <span class="comment-content">{{ comment.content }}</span>
            <div class="sub-comment-list">
              <div v-for="subComment in comment.children" :key="subComment.id" class="sub-comment-item bg ">
                <div class="sub-comment-header">
                  <img :src="subComment.user_avatar" alt="avatar" class="sub-comment-avatar"/>
                  <span class="sub-comment-author">{{ subComment.username }}</span>
                  <span class="sub-comment-meta">
                    <span class="sub-comment-time">{{ subComment.created_at }}</span>
                    <span class="sub-comment-likes">{{ subComment.likes }} 赞</span>
                  </span>
                </div>
                <span class="sub-comment-content">{{ subComment.content }}</span>
              </div>
              <el-input
                  v-model="comment.newSubComment"
                  type="text"
                  placeholder="回复评论"
                  @keyup.enter="addSubComment(comment)"
              />
              <el-button type="text" @click="addSubComment(comment)">回复</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="remen">
      <remen/>
      <el-drawer v-model="drawerVisible" title="合集目录 001-100" size="50%">
        <div class=" papy" @click="share" v-if="!isshare_code">

          <span class=""
                style="color: #fff;  font-weight: bold; margin-bottom: 10px;">分享观看（只有一次机会，后续巡回流出）   点击获取邀请码：{{
              shares
            }}</span>
        </div>

        <!--        <div>-->
        <!--          <div v-if="picUrl" class="paply">-->
        <!--            <img :src="picUrl" alt="支付二维码"/>-->
        <!--            <div class="" style="margin-left: 10px">-->
        <!--              <p>{{ orderData.msg }}</p>-->
        <!--              <p>订单号: {{ orderData.trade_no }}</p>-->
        <!--              <h3 style="font-size: 18px;background-color: #f0f0f0;padding: 2px">金额: {{ orderData.price }}</h3>-->
        <!--              <h3>剩余支付时间：{{ countdown }}</h3>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </div>-->


        <details class="wp-block-details is-layout-flow wp-block-details-is-layout-flow papy">
          <summary>个人介绍:</summary>
          {{ itms.text }}
        </details>
        <div class="papy">
          <span class="">
            <el-icon><Lollipop/></el-icon>
            浏览量：{{ itms.views }}
          </span>
          <span class="">
            <el-icon><Promotion/></el-icon>

          </span>
        </div>

        <div v-html="this.detailStore.detail['collection']"></div>
      </el-drawer>
    </div>
  </div>
  <!-- 预览对话框 -->
  <el-dialog v-model="dialogVisible" :title="currentImage.caption" width="90%">
    <el-image :src="currentImage" alt="预览" class="preview-image" fit="cover"/>
  </el-dialog>

  <div class="but">
    <footers/>
  </div>

  <!-- 悬浮开关按钮 -->
  <div class="floating-button" @click="toggleDrawer">
    <el-icon>
      <Collection/>
    </el-icon>
  </div>
</template>

<script>
import {ElCard, ElCol, ElDialog, ElImage, ElRow, ElInput, ElButton} from 'element-plus';
import {detailStore} from "@/stores/detail.js";
import {Collection, Lollipop, Promotion, Share} from '@element-plus/icons-vue';
import {formatDate} from "@vueuse/shared";
import api from "@/api/api.js";

export default {
  name: 'Detail',
  components: {
    Share,
    Promotion,
    Lollipop,
    ElRow,
    ElCol,
    ElCard,
    ElDialog,
    ElImage,
    Collection,
    ElInput,
    ElButton,
  },
  data() {
    return {
      detailStore: detailStore(),
      drawerVisible: false, // 控制侧边栏显示
      dialogVisible: false, // 控制对话框显示
      currentImage: {},
      newComment: '',
      piv: false,
      picUrl: null,
      shares: null,
      orderData: {
        msg: '',
        price: null,
        qrcode: '',
        trade_no: ''
      },
      countdown: 0, // 倒计时时间（秒）
      countdownInterval: null, // 倒计时定时器
      isOrdering: false, // 是否正在下单
      isshare_code: false // 是否正在下单
    };
  },
  computed: {
    columnSpan() {
      return window.innerWidth < 1250 ? 12 : 8;
    },
    id() {
      return this.$route.params.id;
    },
    itms() {
      if (this.detailStore.detail) {
        if (this.detailStore.detail.imageSrc.length > 6) {
          this.piv = true;
        }
        console.log('itms computed:', this.detailStore.detail['collection']); // 检查 collection 的值
        return this.detailStore.detail;
      } else {
        console.log('itms computed: detail is empty');
        return {}; // 返回一个默认值或空对象
      }
    },
    commentList() {
      const comments = this.detailStore.commentList;
      return comments.map(comment => {
        return {
          ...comment,
          newSubComment: ''
        };
      });
    },
  },
  mounted() {
    this.loadData();
    window.addEventListener('resize', this.handleResize);

    // 等待所有异步操作完成后再进行 itms 的访问
    Promise.all([this.detailStore.fetchUserInfo(this.id), this.detailStore.fetchcommentList(this.id)]).then(() => {
      this.$nextTick(() => {
        if (this.detailStore.detail) {
          console.log('mounted:', this.detailStore.detail['collection']); // 检查 collection 的值
        } else {
          console.log('mounted: detail is null');
        }
      });
    });
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    formatDate,
    async addComment() {
      if (this.newComment.trim() !== '') {
        const newComment = {
          post_id: this.id,
          content: this.newComment,
          created_at: this.getBeijingTime(),
          is_deleted: false,
          likes: 0,
          parent: null,
          newSubComment: ''
        };
        await this.detailStore.addComment(newComment);
        this.newComment = '';
      }
    },
    addSubComment(comment) {
      if (comment.newSubComment.trim() !== '') {
        const newSubComment = {
          post_id: this.id,
          content: comment.newSubComment,
          created_at: this.getBeijingTime(),
          is_deleted: false,
          likes: 0,
        };
        this.detailStore.addSubComment(comment.id, newSubComment);
        comment.newSubComment = '';
      }
    },
    getBeijingTime() {
      const date = new Date();
      const beijingTime = new Date(date.getTime() + (8 * 60 * 60 * 1000)); // 转换为UTC+8
      return beijingTime.toISOString();
    },
    async loadData() {

      this.loadPosts();
    },
    async fotersdeta(id) {
      try {
        await this.detailStore.fetchUserInfo(id);
        await this.detailStore.fetchcommentList(id);
      } catch (error) {
        console.error('Failed to fetch user info:', error);
      }
    },
    ordil() {
      console.log('ordil');

      // 显示加载状态，让用户知道订单正在处理中
      this.loading = true;
      this.isOrdering = true; // 标记正在下单

      api.post('/detail/orderimg', {"id": this.id})
          .then(res => {
            console.log(res);
            if (res.data.code === 0) {
              window.open(res.data.data.payurl, '_blank')

              // this.picUrl = res.data.data.qrcode;
              // this.orderData = {
              //   msg: res.data.data.msg,
              //   price: res.data.data.price,
              //   qrcode: res.data.data.qrcode,
              //   trade_no: res.data.data.trade_no
              // };

              // 启动倒计时，有效时间为3分钟（180秒）
              // this.countdown = 180;
              // this.countdownInterval = setInterval(() => {
              //   if (this.countdown > 0) {
              //     this.countdown--;
              //   } else {
              //     // 倒计时结束，清除定时器
              //     clearInterval(this.countdownInterval);
              //     this.countdownInterval = null;
              //     this.isOrdering = false; // 标记下单完成
              //     this.$message.warning('支付时间已过，请重新下单');
              //     // 你可以在这里添加其他倒计时结束后的操作
              //     this.picUrl = null;
              //     this.orderData = {
              //       msg: '',
              //       price: null,
              //       qrcode: '',
              //       trade_no: ''
              //     }
              //   }
              // }, 1000);
              // this.$message.success('图片成功，请耐心等待');

            } else {
              // 处理非成功的状态码
              this.$message.error(res.data.message || '订单处理失败，请稍后再试');
            }
          })
          .catch(error => {
            // 捕获请求错误，并提示用户
            console.error('订单请求失败:', error);
            this.$message.error('订单请求失败，请检查是否已购买或未登录');
          })
          .finally(() => {
            // 请求完成后，无论成功或失败，都关闭加载状态
            this.loading = false;
          });
    },
    share() {
      console.log('share');

      api.post('/detail/share', {"id": this.id}).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.$message.success('获取分享链接成功，感谢支持，后续更新更多精彩内容！');
          this.shares = res.data.data;

        } else {
          this.$message.error(res.data.message || '分享失败，请稍后再试');
        }
      }).catch(error => {
        console.error('分享失败:', error);
      }).finally(() => {
        // console.log('分享成功');
      });

    },
    loadPosts() {
      this.detailStore.loadpostsFromLocalStorage();
    },
    handleResize() {
      this.$forceUpdate();
    },
    openDialog(image) {
      this.currentImage = image;
      this.dialogVisible = true;
    },
    toggleDrawer() {
      this.drawerVisible = !this.drawerVisible;
    },
  },
};
</script>

<style scoped>
/* 你的样式 */
</style>

<style scoped>
  .papy {
    background-image: linear-gradient(to right, #770fe7 0%, #30eb94 100%);
    border-radius: 10px;
    padding: 10px;
    margin-top: 20px;
  }
@media (min-width: 1250px) {
  .paply {
    display: flex;
    justify-content: center;
    align-items: center;

  }

  .disabled {
    pointer-events: none; /* Disable mouse events */
    opacity: 0.6; /* Use visual indication for disabling */
  }

  .con_rig_but {
    display: flex;
    margin-top: 20px;
    width: 100%;
    align-items: stretch;
    flex-direction: column;
    justify-content: center;

    backdrop-filter: blur(3px) brightness(88%);
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 5px;


  }

  .papy {
    cursor: pointer; /* 确保光标为手状 */

    background-image: linear-gradient(to right, #770fe7 0%, #30eb94 100%);
    border-radius: 10px;
    padding: 10px;
    margin-top: 20px;
  }

  .item {
    cursor: pointer; /* 确保光标为手状 */
  }

  .item img {
    width: 300px;
    height: 400px;
  }

  .cont {
    margin-top: 100px;
    display: flex;
    width: 100%;
    height: 100%;
    flex-direction: row;
    justify-content: center;
    align-items: flex-start;
  }

  .el-card {
    width: 340px;
    height: 466px;
  }

  .con {
    width: 1100px;
  }

  .con_rig {
    display: flex;
    justify-content: flex-end;
    flex-direction: column;
    align-items: flex-end;
  }

  .bg {
    background-image: linear-gradient(to right, #770fe7 0%, #30eb94 100%);
    -webkit-background-clip: text; /* 用于Safari */
    background-clip: text;
    color: transparent; /* 使文本颜色透明，显示背景渐变 */
  }

  .rig_con {
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(3px) brightness(88%);
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 5px;
    margin: 0 auto;
  }

  .sub-comment-avatar {
    border-radius: 50%;
    width: 50px;
    height: 50px;
  }


  .remen {
    margin-left: 14px;
    width: 280px;
  }

  .image {
    width: 300px;
    height: 399px;
    object-fit: cover;
  }

  .el-card {
    backdrop-filter: blur(3px) brightness(88%);
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 10px;
    margin: 10px 0;
  }

  .caption {
    text-align: center;
    font-size: 18px;
    color: #606266;
  }

  .preview-image {
    z-index: 1000;
    width: 100%; /* 预览图片宽度为100% */
  }

  .floating-button {
    position: fixed;
    bottom: calc(50% - 25px); /* 垂直中间位置 */
    right: 20px;
    background-color: #409EFF;
    color: white;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    z-index: 1001; /* 确保按钮在最上层 */
  }

  .floating-button:hover {
    background-color: #66B3FF;
  }

  .comment {
    margin-top: 20px;
    width: 96%;
    /* margin: 0 auto; */
    margin-right: 42px;

  }

  .input >>> textarea {
    height: 150px !important;
  }

  .comment-list {
    padding: 8px;
    backdrop-filter: blur(1px) brightness(84%);
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 10px;
    margin: 10px 0;
  }

  .comment-item {
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 10px;
    margin: 10px 0;
    padding: 8px;
    background-image: linear-gradient(to right, rgba(231, 69, 15, 0.76) 0%, #eb30cf 100%);
    -webkit-background-clip: text; /* 用于Safari */
    background-clip: text;
    color: transparent; /* 使文本颜色透明，显示背景渐变 */
  }

  .comment-author {
    font-weight: bold;
  }

  .comment-content {
    margin-left: 10px;

  }

  .comment-meta {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
  }

  .comment-time {
    font-size: 12px;
    color: #999;
  }

  .comment-likes {
    font-size: 12px;
    color: #999;
  }

  .sub-comment-list {
    margin-left: 20px;
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 10px 0;
  }

  .sub-comment-item {
    backdrop-filter: blur(3px) brightness(99%);
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 10px;
    margin: 10px 0;
    padding: 8px;
  }

  .sub-comment-author {
    font-weight: bold;
  }

  .sub-comment-content {
    margin-left: 10px;
  }

  .sub-comment-meta {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
  }

  .sub-comment-time {
    font-size: 12px;
    color: #999;
  }

  .sub-comment-likes {
    font-size: 12px;
    color: #999;
  }
}

@media (min-width: 425px) and (max-width: 668px) {


  .papy {
    background-image: linear-gradient(to right, #770fe7 0%, #30eb94 100%);
    border-radius: 10px;
    padding: 10px;
    margin-top: 20px;
  }

  .rig_con {
    background-image: linear-gradient(to right, #770fe7 0%, #30eb94 100%);
    -webkit-background-clip: text; /* 用于Safari */
    background-clip: text;
    color: transparent; /* 使文本颜色透明，显示背景渐变 */
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: row;
    flex-wrap: wrap;
    align-content: center;
  }

  .rig_con h1 {
    font-size: 26px;
  }

  .item {
    margin-bottom: 10px;
  }

  .caption {
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏超出范围的文本 */
    text-overflow: ellipsis; /* 用省略号表示隐藏的文本 */
  }

  .floating-button {
    position: fixed;
    bottom: calc(50% - 25px); /* 垂直中间位置 */
    right: 20px;
    background-color: #409EFF;
    color: white;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    z-index: 1001; /* 确保按钮在最上层 */
  }

  .floating-button:hover {
    background-color: #66B3FF;
  }

  .comment {
    margin-top: 20px;
  }

  .comment-list {
    margin-top: 10px;
  }

  .comment-item {
    margin-bottom: 10px;
  }

  .comment-author {
    font-weight: bold;
  }

  .comment-content {
    margin-left: 10px;
  }

  .sub-comment-list {
    margin-left: 20px;
    margin-top: 10px;
  }

  .sub-comment-item {
    margin-bottom: 5px;
  }

  .sub-comment-author {
    font-weight: bold;
  }

  .sub-comment-content {
    margin-left: 10px;
  }




  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: center;
    align-items: center;
  }
  :deep(.el-col-10) {
    flex-grow: 1;
    max-width: 50%;
  }

  .el-row {
    /* box-sizing: border-box; */
    display: flex;
    flex-wrap: wrap;
    position: relative;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
  }

  .post-module-thumb {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .post-info p  {
  display: inline-block; /* 允许块级样式 */
  width: 100%; /* 根据需要调整宽度 */
  max-width: 200px; /* 设置最大宽度 */
  overflow: hidden; /* 隐藏溢出部分 */
  white-space: nowrap; /* 不换行 */
  text-overflow: ellipsis; /* 溢出部分用省略号表示 */
  color: rgba(157, 233, 245, 0.86); /* 链接的颜色（可自定义） */
  text-decoration: none; /* 去掉下划线（可自定义） */
  }

  .el-col {
    margin: 1rem 0;
  }

  .post-thumb {
    min-width: 183px;
    height: 200px;
    border-radius: 4px;
  }
}

@media (min-width: 320px) and (max-width: 425px) {
  :deep(.el-col-10) {
    flex-grow: 1;
    max-width: 50%;
  }

  .post-info p {
overflow: hidden; /* 隐藏溢出部分 */
  white-space: nowrap; /* 不换行 */
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  margin: 0; /* 消除默认边距 */
  }

  .el-row {
    /* box-sizing: border-box; */
    display: flex;
    flex-wrap: wrap;
    position: relative;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
  }

  .post-module-thumb {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .post-thumb {
    min-width: 133px;
    height: 200px;
    border-radius: 4px;
  }
}
</style>

